<template>
	<div class="register-container">
		<div class="register-box">
			<div class="title">注册</div>
			<el-form
				ref="ruleFormRef"
				style="max-width: 600px; width: 100%"
				:model="ruleForm"
				:rules="rules"
				label-width="auto"
				:hide-required-asterisk="true"
				label-position="left"
				@keyup.enter="onRegister(ruleFormRef)"
			>
				<el-form-item label="用户名" prop="username">
					<el-input :prefix-icon="User" v-model="ruleForm.username" placeholder="请输入用户名" clearable />
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input
						:prefix-icon="Lock"
						v-model="ruleForm.password"
						type="password"
						autocomplete="off"
						clearable
						show-password
					/>
				</el-form-item>
				<el-form-item label="确认密码" prop="confirmPassword">
					<el-input
						:prefix-icon="Lock"
						v-model="ruleForm.confirmPassword"
						type="password"
						autocomplete="off"
						clearable
						show-password
					/>
				</el-form-item>
				<el-form-item style="text-align: center">
					<el-button class="register" type="primary" @click="onRegister(ruleFormRef)">注册</el-button>
				</el-form-item>
			</el-form>
			<div class="back" @click="router.replace({ name: 'login' })">返回登录</div>
		</div>
		<TopTile />
	</div>
</template>
<script lang="ts">
export default {
	name: 'Register',
};
</script>
<script setup lang="ts">
import { reactive, ref } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { User, Lock } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { register } from '../api/index';
import { ElMessage } from 'element-plus';

const router = useRouter();
const { api } = window;

interface RuleForm {
	username: string;
	password: string;
	confirmPassword: string;
}
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
	username: '',
	password: '',
	confirmPassword: '',
});
const rules = reactive<FormRules>({
	username: [{ required: true, message: '请输入用户名，长度至少3个字符', trigger: 'blur', min: 3 }],
	password: [{ required: true, message: '请输入密码,长度6到12位', trigger: 'change', min: 6, max: 12 }],
	confirmPassword: [
		{ required: true, message: '请确认密码', trigger: 'blur' },
		{
			validator: (_rule: any, value: string, callback: any) => {
				if (value !== ruleForm.password) {
					callback(new Error('两次输入的密码不一致'));
				} else {
					callback();
				}
			},
			trigger: 'blur'
		}
	]
});
const onRegister = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid, fields) => {
		if (valid) {
			try {
				// 调用注册API
				const res = await register({
					username: ruleForm.username,
					password: ruleForm.password,
				});

				if (res.code === 200) {
					// 注册成功，保存用户数据到本地存储
					const saveResult = await api.saveToken({
						username: ruleForm.username,
						password: ruleForm.password,
						rememberUsername: true,
						rememberPassword: false,
					});

					if (saveResult) {
						ElMessage.success('注册成功');
						// 延迟1秒后跳转到登录页面
						setTimeout(() => {
							router.replace({ name: 'login' });
						}, 1000);
					}
				} else {
					ElMessage.error(res.message || '注册失败');
				}
			} catch (error) {
				console.error('注册失败:', error);
				ElMessage.error('注册失败，请稍后重试');
			}
		} else {
			console.log('表单验证失败:', fields);
		}
	});
};
</script>
<style scoped lang="scss">
.register-container {
	width: 100%;
	height: 100vh;
	background: linear-gradient(72deg, #ff62a5, #6b76ff);

	.register-box {
		width: 65%;
		padding: 20px 20px 40px;
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		border-radius: 10px;
		background-color: #fff;
		box-shadow: 0 0 10px rgba(0, 0, 0, 0.4);
		&:hover {
			box-shadow: 0 0 13px #6b76ff;
		}
		.title {
			width: 100%;
			font-size: 20px;
			font-weight: bold;
			text-align: left;
			margin-bottom: 20px;
		}
		.back {
			font-size: 14px;
			font-weight: bold;
			text-align: center;
			color: #c3c4cf;
			cursor: pointer;
			&:hover {
				color: #000;
			}
		}
		.register-box {
			width: 100%;
			text-align: right;
		}
		.register {
			width: 100%;
		}
	}
}
</style>
